package com.cenxi.utils.subject;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.cenxi.utils.constants.TokenConstant;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 权限获取工具类,当前登录人信息存取
 *
 * @author dijia
 */
public class SecurityContextUtil {

    private static final TransmittableThreadLocal<LoginSubject> THREAD_LOCAL = new TransmittableThreadLocal<>();
    /**
     * 获取登录用户信息
     */
    public static LoginSubject getLoginUser() {
        LoginSubject loginSubject = THREAD_LOCAL.get();
        if (loginSubject == null) {
            loginSubject = new LoginSubject();
            THREAD_LOCAL.set(loginSubject);
        }
        return loginSubject;
    }
    /**
     * 存储登录人信息
     */
    public static void setLoginSubject(LoginSubject loginSubject) {
        THREAD_LOCAL.set(loginSubject);
    }

    /**
     * 清除登录人信息
     */
    public static void clearLoginSubject() {
        THREAD_LOCAL.remove();
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken() {
        // 从header获取token标识
        String token = getRequest().getHeader(TokenConstant.AUTHENTICATION);
        return token;
    }

    /**
     * 获取request
     */
    public static HttpServletRequest getRequest() {
        try {
            return getRequestAttributes().getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            return null;
        }
    }

}
